<?php if(!defined('SPRITCH')) { exit(); }

// Spritch - An opensource PHP5 web framework

// Author: Luca Degasperi
// Licence: GNU GPL
// Site: http://www.spritch.org/

// Class: Input
// Summary: This class provides input checking and filtering
// Since: 0.9.1

class input extends spritch
{
	private $xss_filter;
	private $ip_address = false;
	
	public function __construct()
	{
		$this->language = get('language.helper');
		$this->html = get('html.helper');
		
		$this->profiler->log('input class loaded');
		
		$this->xss_filter = $this->configuration->get('xss_filter',false);
		$this->ip_address = $this->ip_address();
		
		$_REQUEST = array();
		$_GET = array();
	
		$_POST = $this->clean_array($_POST);
		$_COOKIE = $this->clean_array($_COOKIE);
	}

	private function clean_array($arr = array())
	{
		$newarr = array();
		foreach($arr as $key => $value)
		{
			$value = $this->clean_value($value);
			$newarr[$key] = $value;
		}
		return $newarr;
	}
	
	private function clean_value($value)
	{
		if($this->xss_filter == 'on')
			$value = $this->xss_filter($value);
			
		if(strpos($value,"\r") !== FALSE)
			$value = strtr($value,array("\r\n" => "\n","\r" => "\n"));
			
		return $value;
		
	}
	
	private function xss_filter($something)
	{
		return $something;
	}
	
	private function get_array($array,$key,$default = null,$xss_filter = false)
	{
		if(array_key_exists($key,$array))
		{
			if($xss_filter == true and $this->xss_filter == 'off')
				return $this->xss_filter($array[$key]);
			else
				return $array[$key];
		}
		else
		{
			if(!is_null($default))
				return $default;
			else
				return false;
		}
	}
	
	public function post($key,$default = null,$xss_filter = false)
	{
		return $this->get_array($_POST,$key,$default,$xss_filter);
	}
	
	public function cookie($key,$default = null,$xss_filter = false)
	{
		return $this->get_array($_COOKIE,$key,$default,$xss_filter);
	}
	
	public function server($key,$default = null,$xss_filter = false)
	{
		return $this->get_array($_SERVER,$key,$default,$xss_filter);
	}
	
	public function ip_address()
	{
		if($this->ip_address)
			return $this->ip_address;

		$ip_address = false;
		if($this->server('REMOTE_ADDR') AND $this->server('HTTP_CLIENT_IP'))
			 $ip_address = $_SERVER['HTTP_CLIENT_IP'];
		else if($this->server('REMOTE_ADDR'))
			 $ip_address = $_SERVER['REMOTE_ADDR'];
		else if($this->server('HTTP_CLIENT_IP'))
			 $ip_address = $_SERVER['HTTP_CLIENT_IP'];
		elseif($this->server('HTTP_X_FORWARDED_FOR'))
			 $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
		if(!$ip_address)
			$ip_address = '0.0.0.0';

		return $ip_address;
	}
	
	public function is_ajax()
	{
		if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) and strtoupper($_SERVER['HTTP_X_REQUESTED_WITH']) == 'XMLHTTPREQUEST')
			return true;
		return false;
	}
	
	public function agent()
	{
		return;
	}
}
?>